/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.edu.ldu.util;

import java.io.*;

/**
 *
 * @author THEKING
 */
public class Translate {

    public static byte[] ObjectToByte(Object obj){
        byte[] buffer = null;
        try{
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            ObjectOutputStream oo = new ObjectOutputStream(bo);
            oo.writeObject(obj);
            oo.writeObject(null);
            buffer = bo.toByteArray();
        }catch(IOException ex){
            ex.printStackTrace();
        }
        return buffer;
    }

    public static Object ByteToObject(byte[] buffer){
        Object obj = null;
        try{
            ByteArrayInputStream bi = new ByteArrayInputStream(buffer);
            ObjectInputStream oi = new ObjectInputStream(bi);
            obj = oi.readObject();
        }catch(IOException | ClassNotFoundException ex){
            ex.printStackTrace();
        }
        return obj;
    }



    private static class MyObjectInputStream extends ObjectInputStream {


        protected MyObjectInputStream() throws IOException, SecurityException {
            super();
        }

        public MyObjectInputStream(InputStream arg0) throws IOException {
            super(arg0);
        }

        protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException{
            String name = desc.getName();
            try {
                if(name.startsWith("cn.edu.ldu."))
                    name = name.replace("cn.edu.ldu.", "");

                return Class.forName(name);

            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            }

            return super.resolveClass(desc);
        }
    }


}
